//
//  SoundService.m
//  CarClub
//
//  Created by 陈区 on 13-1-9.
//  Copyright (c) 2013年 陈区. All rights reserved.
//

#import "SoundService.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@interface SoundService () <AVAudioPlayerDelegate>

@end


@implementation SoundService
@synthesize isCanPlaySound;

+ (SoundService*)sharedSoundService
{
    static SoundService* sharedSrv = nil;
    if (sharedSrv) {
        return sharedSrv;
    }
    sharedSrv = [[SoundService alloc] init];
    return sharedSrv;
}

- (id)init
{
    if (self = [super init]) {
        isCanPlaySound = YES;
//        _musicPlayer = [[AVAudioPlayer alloc]init];
    }
    return self;
}

//播放点击开门声音
- (void)clickDoorOpen
{
    NSString *temp = @"door.wav";
    [self playSoundWithName:temp];
}

//播放开门成功声音
- (void)doorOpenMsg
{
    //是否开启提示声音 默认是false
    NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey:kPlayOpenDoorSoundKey] ?: @"0";
    if (string.length == 0 || [string isEqualToString:@"0"]) {
        return;
    }
    [self playVibrate];
    
    NSString *soundName = [[NSUserDefaults standardUserDefaults]objectForKey:@"SOUNDNAME"];
    soundName = (soundName && soundName.length > 0) ? soundName : @"a1";
    NSString *temp = [NSString stringWithFormat:@"%@.mp3",soundName];
    [self playSoundWithName:temp];
}

//震动
- (void)playVibrate
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}

- (void)playSoundWithName:(NSString *)name
{
    @try {
        NSError* err = nil;
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&err];
        [[AVAudioSession sharedInstance] setActive:YES error:&err];
        
        NSString *path = SEGPicName(name);
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:path]];

        [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
        self.player = [AVPlayer playerWithPlayerItem:playerItem];
        if (!_player)
        {
            NSLog(@"fail to play audio :(");
            return;
        }
        [_player setVolume:1];
    } @catch (NSException *exception) {
        
    } @finally {
        
    }

}

//监听回调
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
    
    if ([keyPath isEqualToString:@"status"]){
        if (playerItem.status == AVPlayerItemStatusReadyToPlay){
            NSLog(@"playerItem is ready");
            [self.player play];
        } else{
            NSLog(@"load break");
        }
    }
}
@end
